package ytt.small.fore.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ytt.small.fore.mapper.UserTokenMapper;
import ytt.small.fore.model.po.UserToken;
import ytt.small.fore.service.UserTokenService;

import java.util.Date;
import java.util.Random;

/**
 * @Author: small_woods
 * @Date: 2020/6/16 21:22
 */
@Service
@Slf4j
public class UserTokenServiceImpl implements UserTokenService {
    //12小时后过期
    private final static Long EXPIRE = Long.valueOf(3600 * 12 * 1000);

    @Autowired
    UserTokenMapper userTokenMapper;


    @Override
    public UserToken create(String username) {
        //生成一个token
        String token = String.valueOf(new Random().nextInt(100000));
        log.info("token:{}",token);

        //过期时间
        Long expireTime = new Date().getTime() + EXPIRE;
        //判断是否生成过token
        UserToken userToken = userTokenMapper.selectByUsername(username);
        if(userToken == null){
            userToken = new UserToken();
            userToken.setUserName(username);
            userToken.setToken(token);
            userToken.setExpireTime(new Date(expireTime));
            userTokenMapper.insert(userToken);
        }else{
            userToken.setUserName(username);
            userToken.setToken(token);
            userToken.setExpireTime(new Date(expireTime));

            //更新token
            userTokenMapper.updateByToken(userToken);
        }

        return userToken;
    }

    @Override
    public UserToken selectByToken(String token) {
        return userTokenMapper.selectByUsername(token);
    }
}
